package main

import "fmt"
import "flag"
import "os"
import "bufio"

import "eh/grammar"

var gf *string = flag.String( "gf", "", "name of grammar file" )

func stringFromFile( fileName string ) string {
    file, _ := os.Open( fileName, os.O_RDONLY, 0 )
    r := bufio.NewReader( file )
    s, _ := r.ReadString( 0 )
    return s
}

func main() {
    flag.Parse()
    fmt.Printf( "grammar tools: gf = %v\n", *gf )
//
    g := grammar.GrammarFromString( stringFromFile( *gf ) )
    defined := make(map[grammar.Word]bool)
    mentioned := make(map[grammar.Word]bool)
//
    for _, rule := range g.Rules {
        defined[rule.Name] = true
    }
    fmt.Printf( "defined = %v\n", defined )
    fmt.Printf( "defined[x] = %v\n", defined[grammar.Word("x")] )
    fmt.Printf( "root = %v\n", g.Root )
    for _, rule := range g.Rules {
        fmt.Printf( "%v", rule.Name )
        fmt.Printf( " ::=" )
        scan := rule.Rhs
        for scan != nil {
            name := scan.This.Name
            fmt.Printf( " %v", name )
            mentioned[name] = true
            if scan.This.Precedence > 0 { fmt.Printf( ":%v", scan.This.Precedence ) }
            scan = scan.Rest
        }
        fmt.Printf( "\n" )
    }
    return
//
    for name := range mentioned {
        if !defined[name] {
            fmt.Printf( "name %v mentioned, but never defined.\n", name )
        }
    }  
    for name := range defined {
        if !mentioned[name] {
            fmt.Printf( "name %v defined, but never mentioned.\n", name )
        }
    }
}
